package com.young.shop.service.impl.order;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.young.domain.order.SysOrder;
import com.young.domain.order.SysOrderExample;
import com.young.domain.order.SysOrderExample.Criteria;
import com.young.mapper.order.SysOrderMapper;
import com.young.req.order.GetOrderPageReq;
import com.young.res.order.GetOrderPageRes;
import com.young.shop.service.order.OrderService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 订单服务接口实现类
 * @Author: kangyang
 * @Date: 2021/5/18 18:10
 **/
@Service
public class OrderServiceImpl implements OrderService {
  @Autowired
  private SysOrderMapper sysOrderMapper;

  @Override
  public PageInfo<GetOrderPageRes> getOrderPage(GetOrderPageReq getOrderPageReq) {
    PageInfo<GetOrderPageRes> orderPageResPageInfo = new PageInfo<>();
    if(getOrderPageReq == null) {
      return orderPageResPageInfo;
    }
    Page<Object> page = PageHelper
        .startPage(getOrderPageReq.getCurrent(), getOrderPageReq.getSize());
    SysOrderExample orderExample = new SysOrderExample();
    Criteria criteria = orderExample.createCriteria();
    if(StringUtils.isNotEmpty(getOrderPageReq.getOrderNumber())) {
      criteria.andOrderNumberLike("%" + getOrderPageReq.getOrderNumber() + "%");
    }
    if(getOrderPageReq.getStatus() != null) {
      criteria.andStatusEqualTo(getOrderPageReq.getStatus());
    }
    if(getOrderPageReq.getStartTime() != null) {
      criteria.andCreateTimeGreaterThan(getOrderPageReq.getStartTime());
    }
    if(getOrderPageReq.getStartTime() != null) {
      criteria.andCreateTimeGreaterThan(getOrderPageReq.getStartTime());
    }
    List<SysOrder> orders = sysOrderMapper.selectByExample(orderExample);
    List<GetOrderPageRes> getOrderPageRes = createOrderPageRes(orders);
    orderPageResPageInfo.setTotal(page.getTotal());
    orderPageResPageInfo.setPageNum(page.getPageNum());
    orderPageResPageInfo.setPageSize(page.getPageSize());
    orderPageResPageInfo.setList(getOrderPageRes);
    return orderPageResPageInfo;
  }

  private List<GetOrderPageRes> createOrderPageRes(List<SysOrder> orders) {
    List<GetOrderPageRes> getOrderPageResList = new ArrayList<>();
    if(CollectionUtils.isEmpty(orders)) {
      return getOrderPageResList;
    }
    orders.forEach(order -> {
      GetOrderPageRes  getOrderPageRes = new GetOrderPageRes();
      BeanUtils.copyProperties(order, getOrderPageRes);
      getOrderPageResList.add(getOrderPageRes);
    });
    return getOrderPageResList;
  }
}
